<%-- 
    Document   : post
    Created on : Apr 24, 2012, 4:37:12 PM
    Author     : Asus
--%>

<%@page import="java.net.MalformedURLException"%>
<%@page import="java.net.URL"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.FileReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.FileNotFoundException"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.sql.SQLException"%>
<%@page import="model.TagModel"%>
<%@page import="model.PostModel"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.util.Date"%>
<%@page import="java.net.URISyntaxException"%>
<%@page import="java.net.URI"%>
<%@page import="java.util.HashMap"%>
<%@include file="/connect.jspf" %> 

<%
    if(session.getAttribute("userid")==null) {
        response.sendRedirect("index.jsp");
    }        
%>

<%
    HashMap<String, String> errors = new HashMap<String, String>();

    MultipartRequest multireq = null;
    
    PostModel postModel = new PostModel(con);
    TagModel tagModel = new TagModel(con);

    String title = "";
    String konten_link = "";
    String deskripsi_link = "";
    String youtube_link = "";
    String tag = "";
    boolean errorFlag = false;

    if (request.getContentType() != null) {
        String uploadDir = this.getServletContext().getRealPath("upload");
        multireq = new MultipartRequest(request, uploadDir, 5*1024*1024); // maksimum 5 mb

        if (multireq.getParameter("submitted") != null && multireq.getParameter("submitted").equals("1")) {
            title = multireq.getParameter("title");
            //samain dengan konten yang sebelumnya diisi(hanya konten yang diselek yang terjaga)
            if (multireq.getParameter("title") != null) {
                title = multireq.getParameter("title");
            }
            if (multireq.getParameter("konten_link") != null) {
                konten_link = multireq.getParameter("konten_link");
            }
            if (multireq.getParameter("deskripsi_link") != null) {
                deskripsi_link = multireq.getParameter("deskripsi_link");
            }
            if (multireq.getParameter("youtube_link") != null) {
                youtube_link = multireq.getParameter("youtube_link");
            }
            if (multireq.getParameter("tag") != null) {
                tag = multireq.getParameter("tag");
            }

            //validasi post title
            if (multireq.getParameter("title") != null && multireq.getParameter("title").equals("") || (multireq.getParameter("title") == null)) {
                errors.put("title", "Post's title can't be empty");
                errorFlag = true;
            }

            //validasi link                                                   
            if ((multireq.getParameter("pilihan") != null  && multireq.getParameter("konten_link")!=null &&  !multireq.getParameter("konten_link").isEmpty() && multireq.getParameter("pilihan").equals("link")
                    && !validateURL(multireq.getParameter("konten_link")))
                    || (multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("link") && multireq.getParameter("konten_link").isEmpty())) {                
                errors.put("konten_link", " URL is invalid. Maybe you forgot to add the protocol");
                errorFlag = true;
            }

            //validasi konten image                
            if ((multireq.getParameter("pilihan") != null && multireq.getParameter("img_upload") != null && multireq.getParameter("pilihan").equals("image") && !validateImage(multireq.getFile("img_upload")))
                    || (multireq.getParameter("pilihan")!=null && multireq.getParameter("pilihan").equals("image") && multireq.getFile("img_upload")==null)) {
                errors.put("img_upload", " only image(jpeg or jpg) is allowed to be uploaded and image must below 5 MB size");
                errorFlag = true;
            }

            //validasi tag
            tag = tag.trim();
            if (tag.length() == 0) {
                errors.put("tag", "tag is empty");
                errorFlag = true;
            }
            
            //jika tipe konten tidak dipilih
            if (multireq.getParameter("pilihan") == null || (multireq.getParameter("pilihan") != null && !multireq.getParameter("pilihan").equals("link") && !multireq.getParameter("pilihan").equals("image") && !multireq.getParameter("pilihan").equals("video"))) {                
                errors.put("post_type", "You have to specify the content type ");
                errorFlag = true;
            }

            if (!errorFlag && multireq.getParameter("pilihan") != null && (multireq.getParameter("pilihan").equals("link") || multireq.getParameter("pilihan").equals("image") || multireq.getParameter("pilihan").equals("video"))) {
                //lolos validasi		            
                int ret = insertPost(multireq.getParameter("pilihan"), postModel, tagModel, session, title, konten_link, deskripsi_link, youtube_link, tag, multireq, uploadDir);
                //redirect            
                response.sendRedirect("content.jsp?id=" + ret);
            }            
        }
    }
%>

<%!
    public boolean validateURL(String surl) {
        try {
            URL url = new URL(surl);
        } catch (MalformedURLException ex) {
            return false;
        }
        return true;
    }

    public int insertPost(String postType, PostModel postModel, TagModel tagModel, HttpSession session, String title,
        String konten_link, String deskripsi_link, String youtube_link, String tag, MultipartRequest multireq, String uploadDir) throws SQLException, IOException {
        Date date = new Date();
        int poster_id = Integer.parseInt(session.getAttribute("userid").toString());        
        ArrayList<String> arr_tag = filterTag(tag);

        //masukin tag-tagnya ke database dulu
        for (int i = 0; i < arr_tag.size(); i++) {
            //batesin panjang tiap tag sepanjang 20 karakter
            if(arr_tag.get(i).length() > 20) 
                arr_tag.set(i, arr_tag.get(i).substring(0, 21));            
            //trim leading dan trailing space
            arr_tag.set(i, arr_tag.get(i).trim());
            if (arr_tag.get(i).length() > 0) {
                insertTag(arr_tag.get(i), tagModel);
            } else {
                //buang dari $arr_tag
                arr_tag.remove(i);
            }
        }

        String content = null;
        if (postType.equals("link")) {
            content = konten_link + "\n" + deskripsi_link;
        } else if (postType.equals("image")) {
            int mid = multireq.getFile("img_upload").getName().lastIndexOf(".");            
            if(mid > 0) {
                String extension = multireq.getFile("img_upload").getName().substring(mid+1, multireq.getFile("img_upload").getName().length());            
                content = poster_id + "_" + System.currentTimeMillis() + "." + extension;
            }else{
                content = poster_id + "_" + System.currentTimeMillis() + ".jpg";
            }                        
            uploadImg(multireq.getFile("img_upload"), uploadDir + "\\" + content);
        } else if (postType.equals("video")) {
            content = youtube_link;
        }

        int post_id = postModel.insertPost(title, postType, poster_id, content);

        //masukin relasi post dengan tag ke table post_tag 
        for (String aTag : arr_tag) {
            insertPostTagType(post_id, aTag, tagModel);
        }

        return post_id;
    }

    public void insertTag(String tag, TagModel tagModel) throws SQLException {
        tagModel.insertTag(tag);
    }

    public void insertPostTagType(int post_id, String tagType, TagModel tagModel) throws SQLException {
        ResultSet res = tagModel.getTagInfoByType(tagType);
        
        if(res.next()) {
            //ditemukan tag_type tersebut di tabel tag			            
            insertPostTag(post_id, res.getInt("ID"),tagModel);
        }
    }

    public ArrayList<String> filterTag(String tag) {
        String[] ssplit = tag.split(",");
        ArrayList<String> ret = new ArrayList(ssplit.length);
        for (int i = 0; i < ssplit.length; i++) {
            ret.add(ssplit[i]);
        }
        return ret;
    }
     
    public boolean validateImage(File img) {
        System.out.println("validasi image : " + !img.getName().matches("\\S+\\.((jpg)|(gif))") + " " + (img.length() > 5*1024*1024));
        if(!img.getName().matches("\\S+\\.((jpg)|(gif))") || img.length() > 5*1024*1024)
        {            
            // jika ekstensi image bukan jpg atau gif, atau image size melebihi 5mb
            return false;
        }
        return true;
    }     

    public void insertPostTag(int postId, int tagId, TagModel tagModel) throws SQLException {
        tagModel.insertPostTag(postId, tagId);
    }
    
    public void uploadImg(File file, String savedFilename) throws FileNotFoundException, IOException {                           
       BufferedImage buffimg = ImageIO.read(file);
       System.out.println("TEST : " + savedFilename + " " + file + " " + buffimg);
       ImageIO.write(buffimg, "jpg", new File(savedFilename));
    }
%>

<jsp:include page="header.jsp" />

<!-- Body -->
<div id="bodycontent">
    <div class="contentcontainer">

        <div class="title-text">
            <h1>Posting Konten</h1>
        </div>

        <div class="contentbox">
            <form action="post.jsp" method="POST" enctype="multipart/form-data">
                <div class="form-element1">Judul konten:</div>
                <div class="form-element2"><input type="text" name="title" size="35" value="<%= (multireq!=null && multireq.getParameter("title") != null ? (multireq.getParameter("title")) : (""))%>" />
                    <span class='form-error'> <%= (errors.get("title") != null ? (errors.get("title")) : (""))%> </span></div>
                <br/>
                <div class="form-element1">Tipe konten: <span class='form-error'> <%= (errors.get("post_type") != null ? (errors.get("post_type")) : (""))%> </span></div>
                <br/>
                <div class="form-element1"><input type="radio" name="pilihan" onclick="linkSelected()" value="link" <%= (multireq!=null && multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("link") ? "checked='checked'" : "")%> /> Link </div>
                <br/>
                <div class="form-element1">Link :</div>
                <div class="form-element2"><input type="text" name="konten_link" <%= (multireq!=null &&  multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("link") ? "" : "disabled='disabled'")%> size="35" value="<%= konten_link%>" /><span class='form-error'> <%= (errors.get("konten_link") != null ? (errors.get("konten_link")) : (""))%> </span></div>
                <br/>
                <div class="form-element1">Deskripsi :</div>
                <div class="form-element2"><input type="text" name="deskripsi_link" <%= (multireq!=null && multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("link") ? "" : "disabled='disabled'")%>  size="35" value="<%= deskripsi_link%>" /></div>
                <br/>
                <div class="form-element1"><input type="radio" name="pilihan" onclick="imageSelected()" value="image" <%= (multireq!=null && multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("image") ? "checked='checked'" : "")%> /> Image </div>
                <br/>
                <div class="form-element1">Image Upload : </div>
                <div class="form-element2"><input type="file" name="img_upload" <%= (multireq!=null && multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("image") ? "" : "disabled='disabled'")%>  size="35"/>  <span class='form-error'> <%= (errors.get("img_upload") != null ? (errors.get("img_upload")) : (""))%> </span> </div>
                <br/>
                <div class="form-element1"><input type="radio" name="pilihan" onclick="videoSelected()" value="video" <%= (multireq!=null && multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("video") ? "checked='checked'" : "")%> /> Video </div>
                <br/>
                <div class="form-element1">YouTube Link :</div>
                <div class="form-element2"><input type="text" name="youtube_link" <%= (multireq!=null && multireq.getParameter("pilihan") != null && multireq.getParameter("pilihan").equals("video") ? "" : "disabled='disabled'")%> value="<%= youtube_link%>"  size="35"/></div>
                <br/>
                <div class="form-element1">Tag : </div>
                <div class="form-element2"><input type="text" name="tag" value="<%= tag%>" /> <span class='form-error'> <%= (errors.get("tag") != null ? (errors.get("tag")) : (""))%> </span> </div>
                <br/>
                <input type="hidden" name="submitted" value="1"> 
                <div class="form-element1"><input type="submit" id="post" value="post" /></div>				
            </form>

            <div class="form-element1"><input type="button" id="preview" value="preview" onclick="validate();" /></div>				
            <div id="post-hasil">
            </div>
        </div>		
    </div>
</div>    

<jsp:include page="footer.jsp" />